<?php
header('Access-Control-Allow-Origin:*');
ini_set("display_errors", "On"); //打开错误提示
ini_set("error_reporting", E_ALL); //显示所有错误

define('ROOT', dirname(__FILE__));

$path = "./upload";
if (!realpath($path)) {
  mkdir($path);
}
// echo json_encode($_FILES, JSON_UNESCAPED_UNICODE);
try {
  $f = $_FILES["imgFile"]; // tmp_name
  if (!$f["name"] || strlen($f["name"]) < 3) {
    throw new Exception("没有文件", 1);
  }
  $p = $_POST["path"];
  if (strpos($p, ":")) {
    $p = str_replace("\\", "/", substr($p, strripos($p, ":") + 1) . "/" . $f["name"]);
  }
  if (strpos($p, "..")) {
    throw new Exception("路径非法", 2);
  }
  $rp = ROOT . $path . $p;
  $rpf = dirname($rp);
  if (!is_dir($rpf) && !mkdir($rpf, "0777", true)) {
    throw new Exception("目录不可用", 1);
  }
  if (!move_uploaded_file($f["tmp_name"], $rp)) {
    throw new Exception("文件保存失败", 1);
  }
  echo json_encode($p, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (\Throwable $th) {
  http_response_code(404);
  die;
}
